
import Database from "@tauri-apps/plugin-sql";
import { Resource, invoke } from '@tauri-apps/api/core';

import { homePath, createDirs, getG01DataBase } from '../../utils';

import { remove } from "@tauri-apps/plugin-fs";

import { Application as AppStoreApplication } from '../types';
import { qiniuGetUrl } from "../../services";
import { ComparsionOperator, dsDelete, dsFind, dsFindOne, dsUpdate, dsUpdateByKeys, InstalledApplication } from "../local";
import { INSTALLED_APPLICATION_CLASS_IDENTIFIER } from "../constants";

export const applicationGetIntalledApplications = async (): Promise<Array<InstalledApplication>> => {
    const db = await getG01DataBase();

    let { total, data: items } = await dsFind(0, INSTALLED_APPLICATION_CLASS_IDENTIFIER, {});
    console.log(items);
    if (items) {
        return items.map((item, index) => {
            return {
                id: item.id,
                identifier: item.identifier,
                name: item.name,
                icon: item.icon,
                main: item.main,
                application_type: item.application_type || 'agent',
                version: item.version,
                installed_at: item.installed_at,
                installed_path: item.installed_path,
                options: item.options,
                description: item.description,
            }
        });
    }
    return null;
}



export const applicationSaveApplication = async (obj: InstalledApplication): Promise<number> => {
    let res = await dsUpdateByKeys(0, INSTALLED_APPLICATION_CLASS_IDENTIFIER, [obj.identifier], {
        ...obj
    }, {
        upsert: true,
        primary_key: 'identifier'
    });

    console.log(res);
    return 1;
}

export const applicationGetApplicationByIdentifier = async (identifier: string): Promise<InstalledApplication | null> => {
    let item = null;
    try {
        item = await dsFindOne(0, INSTALLED_APPLICATION_CLASS_IDENTIFIER, {
            attributes: [{
                name: 'identifier',
                operator: ComparsionOperator.Equal,
                value: identifier
            }]
        });;
        console.log(item);
    } catch (err) {
        console.log(err);
    }
    if (item) {
        return {
            id: item.id,
            identifier: item.identifier,
            name: item.name,
            icon: item.icon,
            main: item.main,
            application_type: item.application_type,
            version: item.version,
            installed_at: item.installed_at,
            installed_path: item.installed_path,
            description: item.description,
        }
    }
    return null;
}


export const applicationRemoveApplicationByIdentifier = async (identifier: string): Promise<number> => {

    await dsDelete(0, INSTALLED_APPLICATION_CLASS_IDENTIFIER, {
        attributes: [{
            name: 'identifier',
            operator: ComparsionOperator.Equal,
            value: identifier
        }]
    });
    return 0;
}

export async function applicationWinodwSetUrl(url: string): Promise<Array<any>> {
    const res: Array<any> = await invoke('plugin:mg-platform|window_set_url', {
        url: url
    });
    console.log(url);
    return res;
}

export async function applicationWindowEval(window: string, script: string): Promise<string> {
    const res: string = await invoke('plugin:mg-platform|eval', {
        window: window,
        script: script
    });
    console.log(res);
    return res;
}

export const installApplication = async (application: AppStoreApplication, process?: (process: { percent: number, message?: string }) => Promise<void>): Promise<{ result: boolean, message: string }> => {
    process && await process({ percent: 1, message: '获取文件地址...' });

    let pathIdentifier = application.identifier.replace(/\./g, '$');
    //下载文件,获取到链接
    let urls = await qiniuGetUrl([application.icon, application.download]);
    if (!urls || urls.length < 2) {
        process && await process({ percent: 10, message: '获取文件地址失败' });
        return {
            result: false,
            message: '地址无效！'
        };
    }
    process && await process({ percent: 10, message: '开始创建目录...' });
    let home = await homePath();
    //保存文件,解压安装
    await createDirs(`${home}/icons/`);
    await createDirs(`${home}/applications/${pathIdentifier}/`);
    process && await process({ percent: 15, message: '开始下载图标文件...' });
    await invoke('plugin:mg-platform|file_download', {
        url: urls[0],
        file: `${home}/icons/${application.identifier}.png`,
    });
    process && await process({ percent: 20, message: '开始下载安装包文件...' });
    await invoke('plugin:mg-platform|file_download', {
        url: urls[1],
        file: `${home}/applications/${pathIdentifier}/apk.zip`,
    });
    process && await process({ percent: 60, message: '开始解压文件...' });
    await invoke('plugin:mg-platform|file_unzip', {
        zipFile: `${home}/applications/${pathIdentifier}/apk.zip`,
        filePath: `${home}/applications/${pathIdentifier}/`,
    });
    //插入本地表
    //查询是否存在
    let installedApplicaion = await applicationGetApplicationByIdentifier(application.identifier);
    if (installedApplicaion) {
        installedApplicaion = {
            ...installedApplicaion,
            name: application.name,
            title: application.title || application.name,
            icon: `${home}/icons/${application.identifier}.png`,
            application_type: application.application_type,
            version: application.version,
            installed_path: `${home}/applications/${pathIdentifier}/`,
            options: application.options,
            description: application.description,
        }
    } else {
        installedApplicaion = {
            identifier: application.identifier,
            name: application.name,
            title: application.title || application.name,
            icon: `${home}/icons/${application.identifier}.png`,
            main: '/index.html',
            application_type: application.application_type,
            version: application.version,
            installed_path: `${home}/applications/${pathIdentifier}/`,
            options: application.options,
            description: application.description,
        }
    }
    let insertResult = await applicationSaveApplication(installedApplicaion);

    process && await process({ percent: 100, message: '安装完成' });
    return {
        result: true,
        message: '成功！'
    }
}


export const uninstallApplication = async (identifier: string, process?: (process: { percent: number, message?: string }) => Promise<void>): Promise<{ result: boolean, message: string }> => {
    process && await process({ percent: 1, message: '开始删除文件...' });

    let pathIdentifier = identifier.replace(/\./g, '$');
    let home = await homePath();
    //开始删除文件
    try {
        await remove(`${home}/icons/${identifier}.png`);
        process && await process({ percent: 10, message: '删除图标文件' });
    } catch (error) {
        console.log(error);
    }

    try {
        await remove(`${home}/applications/${pathIdentifier}/apk.zip`);
        process && await process({ percent: 20, message: '删除安装包' });
    } catch (error) {
        console.log(error);
    }

    try {
        await remove(`${home}/applications/${pathIdentifier}/`, { recursive: true });
        process && await process({ percent: 60, message: '删除程序文件' });
    } catch (error) {
        console.log(error);

    }

    //从本地数据库中删除记录
    await applicationRemoveApplicationByIdentifier(identifier);
    process && await process({ percent: 100, message: '卸载完成' });
    return {
        result: true,
        message: '成功！'
    }
}


export default {};